package com.atguigu.gmall.order.receiver;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.model.enums.ProcessStatus;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.order.service.OrderService;
import com.atguigu.gmall.payment.client.PaymentFeignClient;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import org.apache.logging.log4j.message.MapMessage;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author mqx
 * @date 2020-11-21 11:14:23
 */
@Component
public class OrderReceiver {

    @Autowired
    private OrderService orderService;

    @Autowired
    private PaymentFeignClient paymentFeignClient;

    @Autowired
    private RabbitService rabbitService;
    //  监听消息
    @SneakyThrows
    @RabbitListener(queues = MqConst.QUEUE_ORDER_CANCEL)
    public void cancelOrder(Long orderId , Message message, Channel channel){
        //  电商本地：关闭orderInfo , 关闭paymentInfo . 有paymentInfo ,则关闭，没有不需要！
        //  是否需要关闭支付宝的交易记录 closeAlipay
        //  判断orderId
        if (orderId!=null){
            //  查看订单的状态！未支付 IService
            //  select * from order_info where id = orderId;
            OrderInfo orderInfo = orderService.getById(orderId);
            //  判断当前的订单状态！
            //  判断当前订单的支付状态order_status , process_status
            if(orderInfo!=null && "UNPAID".equals(orderInfo.getOrderStatus()) &&
                    "UNPAID".equals(orderInfo.getProcessStatus())){
                //  判断电商是否有交易记录产生
                PaymentInfo paymentInfo = paymentFeignClient.getPaymentInfo(orderInfo.getOutTradeNo());
                if (paymentInfo!=null && "UNPAID".equals(paymentInfo.getPaymentStatus())){
                    //  有交易记录 orderInfo,paymentInfo
                    Boolean flag = paymentFeignClient.checkPayment(orderId);
                    if (flag){
                        //  true 表示有交易记录 ,用户一定扫了二维码！
                        Boolean res = paymentFeignClient.closePay(orderId);
                        if (res){
                            //  true 表示已经关闭支付宝的交易记录了。用户扫了，没有付款！
                            //  关闭paymentInfo,orderInfo;
                            orderService.execExpiredOrder(orderId,"2");
                        }else {
                            //  false 关闭失败， 说明用户已经付款了。
                            this.rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_PAYMENT_PAY,MqConst.ROUTING_PAYMENT_PAY,orderId);
                        }
                    }else {
                        //  没有支付宝的交易记录，但是在电商本地的交易记录是有的paymentInfo
                        //  关闭paymentInfo,orderInfo;
                        orderService.execExpiredOrder(orderId,"2");
                    }
                }else {
                    //  没有交易记录 ，只关闭 orderInfo
                    //  关闭订单！ orderInfo;
                    orderService.execExpiredOrder(orderId,"1");
                }
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }
    }
    //  监听消息！
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_PAYMENT_PAY,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_PAYMENT_PAY),
            key = {MqConst.ROUTING_PAYMENT_PAY}
    ))
    public void updateOrderStatus(Long orderId ,Message message,Channel channel){
        //  判断orderId
        if (orderId!=null){
            //  修改订单的状态 当支付成功的时候，将订单状态改为PAID.
            orderService.updateOrderStatus(orderId,ProcessStatus.PAID);

            //  发送消息给库存！ 通过orderId 查询到发送的消息，
            orderService.sendOrderStatus(orderId);
            //  消息确认消费成功
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }
    }


    //  监听减库存的消息！
    //  {"orderId":"63","status":"DEDUCTED"}

    //    @SneakyThrows
    //    @RabbitListener(queues = MqConst.QUEUE_WARE_ORDER)
    //    public void updateOrders1(String jsonResult, Message message, Channel channel){
    //        //  将这个Json 字符串转换为Map
    //        Map map = JSON.parseObject(jsonResult, Map.class);
    //        //  获取订单Id
    //        String orderId = (String) map.get("orderId");
    //
    //        //  获取减库存结果：
    //        String status = (String) map.get("status");
    //        //  判断减库存状态
    //        if ("DEDUCTED".equals(status)){
    //            //  表示减库存成功
    //            orderService.updateOrderStatus(Long.parseLong(orderId),ProcessStatus.WAITING_DELEVER);
    //
    //        }else{
    //            //  表示减库存是吧
    //            orderService.updateOrderStatus(Long.parseLong(orderId),ProcessStatus.STOCK_EXCEPTION);
    //            //  记录当前哪个订单异常，补货。 人工客服！
    //        }
    //
    //        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    //    }

    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_WARE_ORDER,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_WARE_ORDER),
            key = {MqConst.ROUTING_WARE_ORDER}
    ))
    public void updateOrders(String jsonResult , Message message, Channel channel){

        //  将这个Json 字符串转换为Map
        Map map = JSON.parseObject(jsonResult, Map.class);
        //  获取订单Id
        String orderId = (String) map.get("orderId");

        //  获取减库存结果：
        String status = (String) map.get("status");
        //  判断减库存状态
        if ("DEDUCTED".equals(status)){
            //  表示减库存成功
            orderService.updateOrderStatus(Long.parseLong(orderId),ProcessStatus.WAITING_DELEVER);

        }else{
            //  表示减库存是吧
            orderService.updateOrderStatus(Long.parseLong(orderId),ProcessStatus.STOCK_EXCEPTION);
            //  记录当前哪个订单异常，补货。 人工客服！
        }
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

}
